package com.tianbao54.grpc.service;

import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.io.IOException;

public class GrpcServer {

        private Server server;

        private void start () throws IOException {

            this.server = ServerBuilder.forPort(9999).addService(new MyServiceImpl()).build().start();

            System.out.println("server started");

            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                System.out.println("close jvm.");
                GrpcServer.this.stop();
            }));

        }

        private void stop () {

            if (null != this.server) {
                this.server.shutdown();
            }
        }

        private void await () throws InterruptedException {

            if (null != this.server) {
                this.server.awaitTermination();
            }
        }


        public static void main(String[] args) throws InterruptedException, IOException {

            GrpcServer grpcServer = new GrpcServer();
            grpcServer.start();
            grpcServer.await();

        }
}
